package com.yihubang.taobaokotlin.ui.activity

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.yihubang.taobaokotlin.R
import com.yihubang.taobaokotlin.base.BaseActivity
import com.yihubang.taobaokotlin.ui.fragment.HomeFragment
import com.yihubang.taobaokotlin.ui.fragment.OnSellFragment
import com.yihubang.taobaokotlin.ui.fragment.SearchFragment
import com.yihubang.taobaokotlin.ui.fragment.SelectedFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {

    private lateinit var homeFragment: HomeFragment
    private lateinit var onSellFragment: OnSellFragment
    private lateinit var selectedFragment: SelectedFragment
    private lateinit var searchFragment: SearchFragment
    private lateinit var fm: FragmentManager

    override fun getLayoutResId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        initFragment()
    }

    override fun initEvent() {
        initListener()
    }

    private fun initFragment() {
        homeFragment = HomeFragment()
        onSellFragment = OnSellFragment()
        selectedFragment = SelectedFragment()
        searchFragment = SearchFragment()
        fm = supportFragmentManager
        //设置默认选中项
        switchFragment(homeFragment)
    }

    private fun initListener() {
        main_navigation_bar.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.home ->
                    switchFragment(homeFragment)
                R.id.selected ->
                    switchFragment(onSellFragment)
                R.id.red_packet ->
                    switchFragment(selectedFragment)
                R.id.search ->
                    switchFragment(searchFragment)
            }
            true
        }
    }

    private fun switchFragment(targetFragment: Fragment) {
        val beginTransaction = fm.beginTransaction()
        beginTransaction.replace(R.id.main_page_container, targetFragment)
        beginTransaction.commit()
    }

}